package org.jeecg.modules.door.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.door.entity.LwgyJointDoor;
import org.jeecg.modules.door.entity.LwgyDoorPassword;
import org.jeecg.modules.door.entity.LwgyDoorCard;
import org.jeecg.modules.door.mapper.LwgyDoorPasswordMapper;
import org.jeecg.modules.door.mapper.LwgyDoorCardMapper;
import org.jeecg.modules.door.mapper.LwgyJointDoorMapper;
import org.jeecg.modules.door.service.ILwgyJointDoorService;
import org.jeecg.modules.door.stocket.RedisSubscriber;
import org.jeecg.modules.smoke.util.SocketClientService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.async.DeferredResult;



import org.springframework.data.redis.connection.MessageListener;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import java.io.Serializable;
import java.util.List;
import java.util.Collection;
import java.util.UUID;

/**
 * @Description: 门锁管理
 * @Author: jeecg-boot
 * @Date:   2023-08-08
 * @Version: V1.0
 */
@Service
public class LwgyJointDoorServiceImpl extends ServiceImpl<LwgyJointDoorMapper, LwgyJointDoor> implements ILwgyJointDoorService   {

	@Autowired
	private LwgyJointDoorMapper lwgyJointDoorMapper;
	@Autowired
	private LwgyDoorPasswordMapper lwgyDoorPasswordMapper;
	@Autowired
	private LwgyDoorCardMapper lwgyDoorCardMapper;

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private StringRedisTemplate redisTemplate;

	@Autowired
	private RedisSubscriber redisSubscriber;



	/*@Autowired
	private RedisTemplate<String, Object> redisTemplate;*/
	private final ChannelTopic topic = new ChannelTopic("device-status");

	private  final String IP="192.168.0.120";
	private  final int PORT=8888;

	@Override
	@Transactional
	public void saveMain(LwgyJointDoor lwgyJointDoor, List<LwgyDoorPassword> lwgyDoorPasswordList,List<LwgyDoorCard> lwgyDoorCardList) {
		lwgyJointDoorMapper.insert(lwgyJointDoor);
		if(lwgyDoorPasswordList!=null && lwgyDoorPasswordList.size()>0) {
			for(LwgyDoorPassword entity:lwgyDoorPasswordList) {
				//外键设置
				entity.setDoorId(lwgyJointDoor.getId());
				lwgyDoorPasswordMapper.insert(entity);
			}
		}
		if(lwgyDoorCardList!=null && lwgyDoorCardList.size()>0) {
			for(LwgyDoorCard entity:lwgyDoorCardList) {
				//外键设置
				entity.setDoorId(lwgyJointDoor.getId());
				lwgyDoorCardMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(LwgyJointDoor lwgyJointDoor,List<LwgyDoorPassword> lwgyDoorPasswordList,List<LwgyDoorCard> lwgyDoorCardList) {
		lwgyJointDoorMapper.updateById(lwgyJointDoor);

		//1.先删除子表数据
		lwgyDoorPasswordMapper.deleteByMainId(lwgyJointDoor.getId());
		lwgyDoorCardMapper.deleteByMainId(lwgyJointDoor.getId());

		//2.子表数据重新插入
		if(lwgyDoorPasswordList!=null && lwgyDoorPasswordList.size()>0) {
			for(LwgyDoorPassword entity:lwgyDoorPasswordList) {
				//外键设置
				entity.setDoorId(lwgyJointDoor.getId());
				lwgyDoorPasswordMapper.insert(entity);
			}
		}
		if(lwgyDoorCardList!=null && lwgyDoorCardList.size()>0) {
			for(LwgyDoorCard entity:lwgyDoorCardList) {
				//外键设置
				entity.setDoorId(lwgyJointDoor.getId());
				lwgyDoorCardMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		lwgyDoorPasswordMapper.deleteByMainId(id);
		lwgyDoorCardMapper.deleteByMainId(id);
		lwgyJointDoorMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			lwgyDoorPasswordMapper.deleteByMainId(id.toString());
			lwgyDoorCardMapper.deleteByMainId(id.toString());
			lwgyJointDoorMapper.deleteById(id);
		}
	}


	@Override
	public IPage<LwgyJointDoor> queryPageListCustom(Page<LwgyJointDoor> page, QueryWrapper<LwgyJointDoor> queryWrapper) {
/*		queryWrapper.isNotNull("vb.id");
		queryWrapper.orderByAsc("bed_code");*/
		return page.setRecords(lwgyJointDoorMapper.queryPageListCustom(page,queryWrapper));
	}

	@Override
	public List<LwgyJointDoor> queryCustom(QueryWrapper<LwgyJointDoor> queryWrapper){
		return lwgyJointDoorMapper.queryCustom(queryWrapper);
	}

	@Override
	public List<LwgyJointDoor> selectByMainId(String mainId) {
		return lwgyJointDoorMapper.selectByMainId(mainId);
	}





	//读取锁状态，将请求发送服务器(socket)
	/*public Boolean doorInfo(String deviceNumber){
		try {
			if(oConvertUtils.isNotEmpty(deviceNumber)){
				// 发送响应数据
				String responseHex = deviceNumber+" 80 21 00 16";
				System.out.println("发送获取门锁状态指令 " + responseHex);//8778010102032C00011144
				SocketClientService socketClientService = new SocketClientService();
				socketClientService.sendDataToServer(IP, PORT,  responseHex.replaceAll(" ", ""));

				// 生成唯一标识符
				String taskId = UUID.randomUUID().toString();
				// 存储到Redis
				redisTemplate.opsForValue().set(taskId, "pending");


				// 创建DeferredResult来挂起请求
				DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>(30L, ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).build());

				// 设置超时回调
				deferredResult.onTimeout(() -> {
					redisTemplate.delete(taskId); // 清理未完成的任务
					deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timed out"));
				});

				// 设置完成回调
			//	redisTemplate.convertAndSend(topic.getTopic(), taskId);

				// 监听Redis订阅
			//	redisSubscriber.subscribe();
				redisTemplate.opsForPubSub().addListener((MessageListener) (message, pattern) -> {
					if (message.toString().contains(taskId)) {
						String status = message.toString().split(":")[1];
						if ("success".equals(status)) {
							deferredResult.setResult(ResponseEntity.ok("Command executed successfully."));

						} else {
							deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Command execution failed."));

						}
					}
				}, topic);

				// 监听Redis订阅
				*//*redisTemplate.opsForValue().getOperations().getReactiveOperations().listen(topic)
						.doOnNext(message -> {
							String key = new String(message.getBody());
							String value = new String(message.getChannel());

							if (key.equals(taskId)) {
								if ("success".equals(value)) {
									deferredResult.setResult("Command executed successfully.");
								} else {
									deferredResult.setErrorResult("Command execution failed.");
								}
							}
						})
						.subscribe();*//*
				return true;
			}else{
				return false;
			}

		}catch (Exception e){
			e.printStackTrace(); // 打印异常信息以进行调试
			return false;
		}
	}*/
	@Override
	public Boolean doorInfo(String deviceNumber){
		try {
			if(oConvertUtils.isNotEmpty(deviceNumber)){
				// 发送响应数据
				String responseHex = deviceNumber+" 80 21 00 16";
				System.out.println("发送禁止警报指令 " + responseHex);//8778010102032C00011144
				SocketClientService socketClientService = new SocketClientService();
				socketClientService.sendDataToServer(IP, PORT,  responseHex.replaceAll(" ", ""));
				return true;
			}else{
				return false;
			}

		}catch (Exception e){
			e.printStackTrace(); // 打印异常信息以进行调试
			return false;
		}
	}





}
